package com.lagou.edu.factory;

import com.lagou.edu.utils.TransactionManager;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxy implements MethodInterceptor {
	private Object target;
	private TransactionManager transactionManager;

	public CglibProxy(Object target, TransactionManager transactionManager) {
		this.target = target;
		this.transactionManager = transactionManager;
	}

	@Override
	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
		Object result = null;
		//手动开启事务
		transactionManager.beginTransaction();
		try {
			// 调用原有业务逻辑
			result = method.invoke(target, objects);
			//事务提交
			transactionManager.commit();
		} catch (Exception e) {
			//事务回滚
			transactionManager.rollback();
			e.printStackTrace();
			//抛出异常便于上层servlet捕获，给前台正确提示
			throw e;
		}
		return result;
	}
}
